
from sqlalchemy.orm import Session
from app.utils import biz_sign_util
from app.models.account import SubAccount
from app.services import merchant as merc_svc
from app.services import account as acc_svc
from app import services
from app import utils

def batch_sign_sub_acc_balance(db: Session, merc_no: str = ''):
    print('>> batch_sign_sub_acc_balance')
    #sub_accs = db.query(SubAccount).all()
    failed_list = []
    ret = {}
    try:
        qs = db.query(SubAccount)
        if merc_no:
            primary_acc = services.get_account(db, merc_no)
            qs = qs.filter(SubAccount.primary_acc_no == primary_acc.account_no)
        sub_accs = qs.all()
        for acc in sub_accs:
            try:
                salt_msg = f'{acc.primary_acc_no}.{acc.sub_type}.{acc.balance}'
                print('salt_msg: %s' % salt_msg)
                hashed = biz_sign_util.BizSignUtil.sign_with_sm3(salt_msg)
                acc.balance_sign = hashed
                db.add(acc)
            except Exception as err:
                print('Error: %s' % err)
                print(f'account: {acc.primary_acc_no} -> {acc.sub_type} 签名失败')
                failed_list.append(f'{acc.primary_acc_no}->{acc.sub_type}')
        db.commit()
        print('----------- 处理完成 ----------')
        print('失败记录: ', failed_list)
        ret['summmary'] = summary = f'总数: {len(sub_accs)}, 失败数: {len(failed_list)}'
        print(summary)
        ret['failed_list'] = failed_list
        
    except Exception as err:
        print('查询记录出错, Error: %s' % err)
        ret['error'] = str(err)
    return ret

def batch_verify_sub_acc_signature(db: Session, merc_no: str = ''):
    print('>> batch_verify_sub_acc_signature')
    failed_list = []
    ret = {}
    try:
        qs = db.query(SubAccount)
        if merc_no:
            primary_acc = services.get_account(db, merc_no)
            qs = qs.filter(SubAccount.primary_acc_no == primary_acc.account_no)
        sub_accs = qs.all()
        for acc in sub_accs:
            try:
                salt_msg = f'{acc.primary_acc_no}.{acc.sub_type}.{acc.balance}'
                print('salt_msg: %s' % salt_msg)
                result = biz_sign_util.BizSignUtil.verify_with_sm3(salt_msg, acc.balance_sign)
                if not result:
                    failed_list.append(f'{acc.primary_acc_no}->{acc.sub_type}')
            except Exception as err:
                print('Error: %s' % err)
                print(f'account: {acc.primary_acc_no} -> {acc.sub_type} 验签失败')
                failed_list.append(f'{acc.primary_acc_no}->{acc.sub_type}')
        #db.commit()
        print('----------- 处理完成 ----------')
        print('失败记录: ', failed_list)
        ret['summmary'] = summary = f'总数: {len(sub_accs)}, 失败数: {len(failed_list)}'
        print(summary)
        ret['failed_list'] = failed_list
        
    except Exception as err:
        print('查询记录出错, Error: %s' % err)
        ret['error'] = str(err)
    return ret
    